package cn.tedu._05article.base.exception;

import cn.tedu._05article.base.response.JsonResult;
import cn.tedu._05article.base.response.StatusCode;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalException {
    @ExceptionHandler
    public JsonResult doHandlerMethodArgumentNotValidException(MethodArgumentNotValidException exception) {
        String data = exception.getFieldError().getDefaultMessage();
        log.error("MethodArgumentNotValidException:" + data);
        return new JsonResult(StatusCode.VALIDATED_ERROR, data);
    }

    @ExceptionHandler
    public JsonResult doHandlerConstraintViolationException(ConstraintViolationException exception) {
        String data = exception.getMessage().split(":")[1].trim();
        log.error("ConstraintViolationException:" + data);
        return new JsonResult(StatusCode.VALIDATED_ERROR, data);
    }
}
